<head>
	<style type="text/css" media="screen">@import "../jqt/jqtouch.css";</style>
	<style type="text/css" media="screen">@import "../jqt/theme.css";</style>
	<script src="../jquery.js" type="text/javascript" charset="utf-8"></script>
	<script src="../geoutil.js" type="text/javascript" charset="utf-8"></script>
	<script src="../jqt/jqtouch.js" type="text/javascript" charset="utf-8"></script>
	<script type="text/javascript" charset="utf-8">
	var jQT = new $.jQTouch();
	var cgiPath = '/~mkrieger/cgi-bin/';
	
	function addDistanceInformation(distance, placeholder) {
		$("<li id='distance'>" + Math.floor(distance * 1000) + "m away</li>").appendTo(placeholder);
	}
	
	function getLocationAndDistance(lat, lon, placeholder) {
		if(navigator.geolocation) {
			navigator.geolocation.getCurrentPosition(function(position){
				var dist = distanceBetweenPoints(lat, lon, position.coords.latitude, position.coords.longitude);
				addDistanceInformation(dist, placeholder);
			});
		} else {
			// fake it
			window.setTimeout(function(){
				var dist = distanceBetweenPoints(lat, lon, 37.428337, -122.175822);
				addDistanceInformation(dist, placeholder);
			}, 1000);
		}
	}
	
	
	$(document).ready(function(){
		$.getJSON(cgiPath + 'getcafes.php', function(response){
			for (var cafe in response) {
				var fullname = response[cafe].full_name;
				var address = response[cafe].address;
				var newDiv = $("<div class='cafe-info'></div>");
				newDiv.attr("id", cafe);
				var newList = $("<ul class='info-list'></ul>").appendTo(newDiv);
				$("<li>" + fullname + "</li>").appendTo(newList);
				$("<li>at: " + address + "</li>").appendTo(newList);
				newDiv.appendTo(document.body);
				$('<li><a href="#' + cafe + '">' + response[cafe].full_name + '</li></a>').appendTo('#cafelist');
				newDiv.bind("pageAnimationEnd", function() {
					var cafeID = '#' + $(this).attr("id");
					var thisCafe = response[$(this).attr("id")];
					if (!$("#distance", cafeID).length) {
						$.getJSON("http://tinygeocoder.com/create-api.php?callback=?", {'q': thisCafe.address}, function(data){
							var lat = data[0];
							var lon = data[1];
							getLocationAndDistance(lat, lon, $(".info-list", cafeID ));
						})
					}
				});
			}
		})
	})
</script>
</head>
<body>
	<div id="home" class="current">
		<ul id="cafelist"></ul>
	</div>
</body>